package com.zhida.jiyangcenter.modle

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.view.MotionEvent
import android.widget.EditText
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.resColor
import chooongg.base.utils.tipFail
import chooongg.base.utils.tipSuccess
import chooongg.base.utils.toast
import chooongg.http.APIException
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.vehicle.inspection.api.toRequestBody
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIZaxiang
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.order.adapter.CommentAdapter
import com.zhida.jiyangcenter.order.adapter.PhotoInfo
import com.zhida.jiyangcenter.utils.FilterUtil
import com.zhida.jiyangcenter.utils.GlideEngine
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_updata_report.*
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.util.ArrayList
import java.util.HashMap

@TitleBar(false)
@ContentLayout(R.layout.activity_updata_report)
class UpdataReportActivity : BaseActivity() {
    private val mPhotoInfos = ArrayList<PhotoInfo>()
    private val MAX_NUM = 3
    private var mTempPhotoInfo: PhotoInfo? = null
    private var mPhotoIndex = 1
    private var mAdapter: CommentAdapter? = null
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.title("上传报告").navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }.operationText("提交") {
            if (mPhotoInfos.size == 1) {
                toast("请上传您的体检报告")
            } else {
                commit()
            }
        }.getOperationTextView().apply {
            setTextColor(resColor(R.color.white))
        }
        recycler_view.layoutManager = GridLayoutManager(this, 3)
        addAddImageData()
        mAdapter = CommentAdapter(mPhotoInfos, object : CommentAdapter.DelPhotoListener {
            override fun delPhoto(path: String) {
                delItem(path)
            }

            override fun addPhoto() {
                selectImage()
            }
        })
        recycler_view.adapter = mAdapter
        edit_opinion.setOnTouchListener { view, event ->
            //触摸的是EditText而且当前EditText能够滚动则将事件交给EditText处理。否则将事件交由其父类处理
            if (view.getId() == R.id.edit_miaoshu && canVerticalScroll(edit_opinion)) {
                view.getParent().requestDisallowInterceptTouchEvent(true)
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    view.getParent().requestDisallowInterceptTouchEvent(false)
                }
            }
            false
        }
        edit_opinion.filters = arrayOf(
            FilterUtil.getInputFilter(
                this,
                "不支持输入表情或者特殊符号", FilterUtil.MATCHER_DEFAULT
            ), InputFilter.LengthFilter(200)
        )

    }

    private fun commit() {
        val datas = HashMap<String, RequestBody>()
        for (i in 0 until mPhotoInfos.size) {
            if (mPhotoInfos[i].localUrl != "发布") {
                val cardFrontFile = File(mPhotoInfos[i].localUrl)
                val requestFrontBody = RequestBody.create(MultipartBody.FORM, cardFrontFile)
                datas["picture" + (i+1) + "\"; filename=\"" + cardFrontFile.name] =
                    requestFrontBody
            }
        }
        lifecycleScope.request({
            APIZaxiang.service().examinationAdd(edit_opinion.text.toString().toRequestBody(), datas)
        }, object : BaseAPI<Any>() {
            override fun onSuccess(t: Any?, state: Int, msg: String) {
                tipSuccess(msg)
                finish()
            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }

        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1004) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                val selectList = PictureSelector.obtainMultipleResult(data)
                addPhotoNotify(
                    when {
                        !selectList[0].compressPath.isNullOrEmpty() -> selectList[0].compressPath
                        !selectList[0].cutPath.isNullOrEmpty() -> selectList[0].cutPath
                        !selectList[0].androidQToPath.isNullOrEmpty() -> selectList[0].androidQToPath
                        else -> selectList[0].path
                    }
                )
            }
        }
    }

    /**
     * 在页面显示图片
     *
     * @param path
     */
    private fun addPhotoNotify(path: String) {
        if (mPhotoInfos.size >= 1) {
            mPhotoInfos.remove(mPhotoInfos[mPhotoInfos.size - 1])
        }
        if (path.isNotEmpty()) {
            mTempPhotoInfo = PhotoInfo(path, mPhotoIndex)
            mPhotoInfos.add(mTempPhotoInfo!!)
            mPhotoIndex++
        }
        if (mPhotoInfos.size < MAX_NUM) {
            addAddImageData()
        }
        recycler_view.adapter = mAdapter
    }


    fun selectImage() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .selectionMode(PictureConfig.SINGLE)
            .loadImageEngine(GlideEngine.createGlideEngine())
            .previewImage(false)
            .isCamera(true)
            .minimumCompressSize(200)
            .compress(true)
            .isZoomAnim(true)
            .withAspectRatio(1, 1)
            .circleDimmedLayer(true)
            .showCropFrame(false)
            .showCropGrid(false)
            .isDragFrame(true)
            .rotateEnabled(true)
            .scaleEnabled(true)
            .forResult(1004)
    }

    /**
     * EditText竖直方向能否够滚动
     *
     * @param editText 须要推断的EditText
     * @return true：能够滚动   false：不能够滚动
     */
    private fun canVerticalScroll(editText: EditText): Boolean {
        //滚动的距离
        val scrollY = editText.scrollY
        //控件内容的总高度
        val scrollRange = editText.layout.height
        //控件实际显示的高度
        val scrollExtent =
            editText.height - editText.compoundPaddingTop - editText.compoundPaddingBottom
        //控件内容总高度与实际显示高度的差值
        val scrollDifference = scrollRange - scrollExtent

        return if (scrollDifference == 0) {
            false
        } else scrollY > 0 || scrollY < scrollDifference - 1

    }


    /**
     * 删除图片
     *
     * @param path
     */
    private fun delItem(path: String) {
        for (info in mPhotoInfos) {
            if (info.localUrl.equals(path)) {
                mPhotoInfos.remove(info)
                break
            }
        }
        if (!"发布".equals(mPhotoInfos[mPhotoInfos.size - 1].localUrl)) {
            addAddImageData()
        }
        mAdapter?.notifyDataSetChanged()
    }

    /**
     * 添加“+选择图片”
     */
    private fun addAddImageData() {
        val addInfo = PhotoInfo("发布", -1)
        mPhotoInfos.add(addInfo)
    }
}